package com.aabte.mybatis.mapper.typehandler;

import com.aabte.mybatis.mapper.bean.Address;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AddressTypeHandler extends BaseTypeHandler<Address> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Address parameter, JdbcType jdbcType) throws SQLException {
        if (null == parameter) {
            return;
        }

        String value = new StringBuilder()
                .append(parameter.getProvince())
                .append(",")
                .append(parameter.getCity())
                .append(",")
                .append(parameter.getStreet())
                .toString();
        ps.setString(i, value);
    }

    @Override
    public Address getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return toAddress(value);
    }

    @Override
    public Address getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return toAddress(value);
    }

    @Override
    public Address getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return toAddress(value);
    }

    private Address toAddress(String value){
        if (StringUtils.isBlank(value)) {
            return null;
        }

        String[] valueArr = value.split(",");
        if (valueArr.length != 3) {
            return null;
        }

        return new Address(
                valueArr[0],
                valueArr[1],
                valueArr[2]);
    }
}
